<?php
// public/trainings/edit.php
declare(strict_types=1);
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../includes/layout.php';
require_once __DIR__.'/../../includes/flash.php';

require_role('admin','hr','trainer');
global $pdo;

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { header('Location: /ldp/public/trainings/index.php'); exit; }

$stmt = $pdo->prepare("SELECT * FROM trainings WHERE id = ?");
$stmt->execute([$id]);
$training = $stmt->fetch();
if (!$training) { set_flash('warning','Training not found.'); header('Location: /ldp/public/trainings/index.php'); exit; }

// Permission: trainer can edit only their own training
if (current_user()['role']==='trainer' && (int)$training['trainer_id'] !== (int)current_user()['id']) {
  http_response_code(403); exit('Forbidden');
}

$trainers = $pdo->query("SELECT id, name FROM users WHERE role='trainer' AND status='active' ORDER BY name ASC")->fetchAll();

$errors = [];
$title = $training['title'];
$description = $training['description'];
$schedule = $training['schedule'];
$trainer_id = $training['trainer_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  verify_csrf();
  $title = trim($_POST['title'] ?? '');
  $description = trim($_POST['description'] ?? '');
  $schedule = trim($_POST['schedule'] ?? '');
  $trainer_id = (int)($_POST['trainer_id'] ?? 0) ?: null;

  if ($title === '' || mb_strlen($title) < 3) $errors['title'] = 'Title must be at least 3 characters.';
  if ($schedule !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $schedule)) $errors['schedule'] = 'Schedule must be YYYY-MM-DD or blank.';

  if (current_user()['role']==='trainer') {
    $trainer_id = (int)current_user()['id'];
  }

  if (empty($errors)) {
    $stmt = $pdo->prepare("UPDATE training SET title=?, description=?, schedule=?, trainer_id=? WHERE id=?");
    $stmt->execute([$title, $description, $schedule ?: null, $trainer_id, $id]);
    set_flash('success','Training updated.');
    header('Location: /ldp/public/trainings/index.php');
    exit;
  }
}

render_header('Edit Training', 'trainings');
?>
<div class="card">
  <div class="card-body">
    <form method="post">
      <?= csrf_field(); ?>
      <div class="form-group">
        <label class="form-required">Title</label>
        <input name="title" class="form-control <?= isset($errors['title'])?'is-invalid':'' ?>" value="<?= htmlspecialchars($title) ?>">
        <?php if(isset($errors['title'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['title']) ?></div><?php endif; ?>
      </div>
      <div class="form-group">
        <label>Description</label>
        <textarea name="description" rows="4" class="form-control"><?= htmlspecialchars($description) ?></textarea>
      </div>
      <div class="form-row">
        <div class="form-group col-md-6">
          <label>Schedule (YYYY-MM-DD)</label>
          <input name="schedule" class="form-control <?= isset($errors['schedule'])?'is-invalid':'' ?>" value="<?= htmlspecialchars($schedule) ?>">
          <?php if(isset($errors['schedule'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['schedule']) ?></div><?php endif; ?>
        </div>
        <div class="form-group col-md-6">
          <label>Trainer</label>
          <?php if (current_user()['role']==='trainer'): ?>
            <input class="form-control" value="<?= htmlspecialchars(current_user()['name']) ?>" disabled>
          <?php else: ?>
            <select name="trainer_id" class="form-control">
              <option value="">— Unassigned —</option>
              <?php foreach ($trainers as $t): ?>
                <option value="<?= (int)$t['id'] ?>" <?= ((int)$trainer_id===(int)$t['id'])?'selected':'' ?>><?= htmlspecialchars($t['name']) ?></option>
              <?php endforeach; ?>
            </select>
          <?php endif; ?>
        </div>
      </div>

      <div class="d-flex justify-content-between">
        <a href="/ldp/public/trainings/index.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Back</a>
        <button class="btn btn-primary"><i class="fas fa-save"></i> Update</button>
      </div>
    </form>
  </div>
</div>
<?php render_footer(); ?>
